// login.js

// 登录相关API配置
const LOGIN_BASE_URL = 'http://localhost:8082' // 后端服务地址

/**
 * 封装微信小程序的网络请求
 */
function request(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: LOGIN_BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      timeout: options.timeout || 10000,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(new Error(`请求失败: ${res.statusCode} - ${res.data?.message || '未知错误'}`))
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', err)
        reject(new Error(`网络请求失败: ${err.errMsg || '连接超时'}`))
      }
    })
  })
}

/**
 * 登录相关API
 */
const loginApi = {
  // 发送验证码
  sendCode(phoneNumber) {
    return request({
      url: '/login/sendCode',
      method: 'POST',
      data: {
        phoneNumber: phoneNumber
      }
    })
  },

  // 验证码登录
  verifyCode(phoneNumber, code) {
    return request({
      url: '/login/verifyCode',
      method: 'POST',
      data: {
        phoneNumber: phoneNumber,
        code: code
      }
    })
  },

  // 用户名密码登录
  loginByPassword(username, password) {
    return request({
      url: '/login/loginByPassword',
      method: 'POST',
      data: {
        username: username,
        password: password
      }
    })
  },

  // 验证token
  validateToken(token) {
    return request({
      url: '/login/validateToken',
      method: 'POST',
      data: {
        token: token
      }
    })
  },

  // 获取用户手机号
  getUserPhone(token) {
    return request({
      url: '/login/getUserPhone',
      method: 'POST',
      data: {
        token: token
      }
    })
  },

  // 获取第一个用户手机号（用于未登录用户）
  getFirstUserPhone() {
    return request({
      url: '/login/getFirstUserPhone',
      method: 'GET'
    })
  }
}

Page({
  data: {
    phone: '',
    code: '',
    username: '',
    password: '',
    codeBtnText: '获取验证码',
    codeBtnDisabled: false,
    countdown: 0,
    isLogging: false, // 密码登录状态
    isWechatLogging: false, // 微信登录状态
    loginType: 'phone', // 'phone' 或 'password'
    showWechatPopup: false,
    maskedPhone: '' // 从数据库获取，不硬编码
  },

  // 手机号输入
  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  // 验证码输入
  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    })
  },

  // 用户名输入
  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    })
  },

  // 密码输入
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
  },

  // 切换登录方式
  onSwitchLoginType(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      loginType: type,
      phone: '',
      code: '',
      username: '',
      password: '',
      codeBtnText: '获取验证码',
      codeBtnDisabled: false,
      countdown: 0
    })
  },

  // 发送验证码
  async onSendCode() {
    const phone = this.data.phone
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }

    try {
      wx.showLoading({
        title: '发送中...'
      })

      const result = await loginApi.sendCode(phone)
      
      wx.hideLoading()
      
      if (result.code === 200) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        // 开始倒计时
        this.startCountdown()
      } else {
        wx.showToast({
          title: result.message || '发送失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('发送验证码失败:', error)
      wx.showToast({
        title: error.message || '发送失败，请重试',
        icon: 'none'
      })
    }
  },

  // 开始倒计时
  startCountdown() {
    let countdown = 60
    this.setData({
      codeBtnDisabled: true,
      codeBtnText: `${countdown}s后重发`,
      countdown: countdown
    })

    const timer = setInterval(() => {
      countdown--
      if (countdown <= 0) {
        clearInterval(timer)
        this.setData({
          codeBtnDisabled: false,
          codeBtnText: '获取验证码',
          countdown: 0
        })
      } else {
        this.setData({
          codeBtnText: `${countdown}s后重发`,
          countdown: countdown
        })
      }
    }, 1000)
  },

  // 登录
  async onLogin() {
    const { phone, code, username, password, isLogging, loginType } = this.data
    
    if (isLogging) return
    
    // 根据登录类型进行不同的验证
    if (loginType === 'phone') {
      if (!phone) {
        wx.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      if (!code) {
        wx.showToast({
          title: '请输入验证码',
          icon: 'none',
          duration: 2000
        })
        return
      }
    } else if (loginType === 'password') {
      if (!username) {
        wx.showToast({
          title: '请输入用户名',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      if (!password) {
        wx.showToast({
          title: '请输入密码',
          icon: 'none',
          duration: 2000
        })
        return
      }
    }

    // 设置登录状态
    this.setData({
      isLogging: true
    })

    // 显示加载动画
    wx.showLoading({
      title: '登录中...',
      mask: true
    })

    try {
      let result
      if (loginType === 'phone') {
        result = await loginApi.verifyCode(phone, code)
      } else {
        result = await loginApi.loginByPassword(username, password)
      }
      
      wx.hideLoading()
      
      if (result.code === 200) {
        // 登录成功动画
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        })
        
        // 保存用户信息和token
        const { token, userInfo } = result.data
        userInfo.token = token
        
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('token', token)
        
        // 更新全局数据
        const app = getApp()
        app.setUserInfo(userInfo)

        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/user/user',
            success: () => {
              this.setData({
                isLogging: false
              })
            },
            fail: () => {
              this.setData({
                isLogging: false
              })
            }
          })
        }, 1500)
      } else {
        wx.showToast({
          title: result.message || '登录失败',
          icon: 'none'
        })
        this.setData({
          isLogging: false
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('登录失败:', error)
      wx.showToast({
        title: error.message || '登录失败，请重试',
        icon: 'none'
      })
      this.setData({
        isLogging: false
      })
    }
  },

  // 微信登录
  onWechatLogin() {
    const { isWechatLogging } = this.data
    
    if (isWechatLogging) return
    
    // 直接显示微信登录弹窗，不查询数据库
    this.showWechatLoginPopup()
  },

  // 显示微信登录弹窗
  showWechatLoginPopup() {
    // 使用指定手机号13052651019
    const specificPhone = '13052651019'
    const maskedPhone = this.maskPhone(specificPhone)
    
    this.setData({
      maskedPhone: maskedPhone,
      showWechatPopup: true
    })
    
    console.log('显示微信登录弹窗，手机号:', maskedPhone)
  },

  // 手机号脱敏处理
  maskPhone(phone) {
    if (!phone || phone.length < 7) {
      return phone
    }
    return phone.substring(0, 3) + '****' + phone.substring(7)
  },

  // 关闭弹窗
  onClosePopup() {
    this.setData({
      showWechatPopup: false
    })
  },

  // 允许登录
  async onAllowLogin() {
    this.setData({
      showWechatPopup: false,
      isWechatLogging: true
    })
    
    wx.showLoading({
      title: '登录中...',
      mask: true
    })

    try {
      // 使用指定用户的用户名密码进行登录
      const username = 'wx_xaJlG4rY'
      const password = '123456'
      
      console.log('使用用户名密码登录:', username)
      
      const result = await loginApi.loginByPassword(username, password)
      
      wx.hideLoading()
      
      if (result.code === 200) {
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        })
        
        // 保存用户信息和token
        const { token, userInfo } = result.data
        wx.setStorageSync('token', token)
        wx.setStorageSync('userInfo', userInfo)
        
        // 更新全局数据
        const app = getApp()
        app.setUserInfo(userInfo)

        setTimeout(() => {
          wx.switchTab({
            url: '/pages/user/user',
            success: () => {
              this.setData({
                isWechatLogging: false
              })
            },
            fail: () => {
              this.setData({
                isWechatLogging: false
              })
            }
          })
        }, 1500)
      } else {
        wx.showToast({
          title: result.message || '登录失败',
          icon: 'none',
          duration: 2000
        })
        this.setData({
          isWechatLogging: false
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('微信登录失败:', error)
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none',
        duration: 2000
      })
      this.setData({
        isWechatLogging: false
      })
    }
  },

  // 取消登录
  onCancelLogin() {
    this.setData({
      showWechatPopup: false
    })
    
    wx.showToast({
      title: '已取消登录',
      icon: 'none',
      duration: 1500
    })
  },

  // 用户协议
  onAgreementTap() {
    wx.showToast({
      title: '用户协议',
      icon: 'none'
    })
  },

  // 隐私政策
  onPrivacyTap() {
    wx.showToast({
      title: '隐私政策',
      icon: 'none'
    })
  }
})
